<?php


	namespace app\index\controller;


	use think\Controller;
	use think\Request;

	class Skill extends Controller
	{


		public $redis;

		const SKILLKEY    = 'secdoc_skill_key_goods_id';
		const SKILLMEMBER = 'secdoc_skill_goods_member';

		public function __construct () {
			$this->redis = new \Redis();
			$this->redis->connect('127.0.0.1', 6379);
			$this->redis->auth('123456');
		}

		public function index () {


		}


		public function addGoods () {
			//一开始存入是个商品
			$goods_id = 12;
			$skill_key = self::SKILLKEY . '_' . $goods_id;

			//使用列表,将商品id=12的商品加入到秒杀库存中

			for ($i = 1; $i <= 10; $i++) {
				$this->redis->lPush($skill_key, 1);
			}
		}

		public function buyGoods (Request $request) {
			$user_id = intval($request->param('user_id'));

			$goods_id = 12;
			$skill_goods_key = self::SKILLKEY . '_' . $goods_id;

			//获取该商品的库存
			$skill_member_key = self::SKILLMEMBER . '_' . $goods_id;
			$stock = $this->redis->lLen($skill_goods_key);

			if ($stock > 0) {//库存存在表示活动还在开始
				//检测该用户是否购买过该商品(利用集合的唯一性来判断该用户是否购买过该商品了)
				if ($this->redis->sIsMember($skill_member_key, $user_id)) {
					echo '对不起您已购买过了,不能重复购买';
					die;
				}

				//扣除库存
				if (!$this->redis->lPop($skill_goods_key)) {
					return '对不起已售罄';
					die;
				};

				//记录谁购买了(记录到集合中去,集合有唯一性,避免重复购买)
				$this->redis->sAdd($skill_member_key, $user_id);
				echo '恭喜您:' . $user_id . ',抢购成功';
				die;
			} else {
				//抢购完成后加入订单中去
				$user_list = $this->redis->sMembers($skill_member_key);
				if ($user_list) {
					foreach ($user_list as $user) {
						$data = [
							'goods_id' => $goods_id,
							'user_id'  => $user,
							'num'      => 1
						];
						//入库
					}
				}
				echo '请购活动结束了';
			}
		}


		//异步购买的流程
		public function ansycBuyGoods(Request $request){
			$user_id = intval($request->param('user_id'));
			$goods_id = 12;
			$skill_goods_key = self::SKILLKEY . '_' . $goods_id;
			//获取该商品的库存
			$skill_member_key = self::SKILLMEMBER . '_' . $goods_id;
			$stock = $this->redis->lLen($skill_goods_key);
			if ($stock > 0) {//库存存在表示活动还在开始
				//检测该用户是否购买过该商品(利用集合的唯一性来判断该用户是否购买过该商品了)
				if ($this->redis->sIsMember($skill_member_key, $user_id)) {
					return $this->returnError('对不起您已购买过了,不能重复购买');
				}

				//扣除库存
				if (!$this->redis->lPop($skill_goods_key)) {
					return $this->returnError('对不起已售罄');
				};

				//记录谁购买了(记录到集合中去,集合有唯一性,避免重复购买)
				$this->redis->sAdd($skill_member_key, $user_id);
				return $this->returnError('购买成功',1);
			}
		}



	}